package edu.yzu.testspringboot002.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.PasswdStrength;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import edu.yzu.testspringboot002.common.constant.CacheColumnFamilyConstants;
import edu.yzu.testspringboot002.common.constant.RedisUserKeyConstants;
import edu.yzu.testspringboot002.config.handler.PwdUtil;
import edu.yzu.testspringboot002.config.wechat.WxMaProperties;
import edu.yzu.testspringboot002.convert.DoctorsConvertMapper;
import edu.yzu.testspringboot002.exception.BizException;
import edu.yzu.testspringboot002.po.Doctor;
import edu.yzu.testspringboot002.po.WeChatDTO;
import edu.yzu.testspringboot002.po.dto.PasswordUpdateDTO;
import edu.yzu.testspringboot002.po.vo.AppUserInfo;
import edu.yzu.testspringboot002.po.vo.AppUserVO;
import edu.yzu.testspringboot002.utils.RocksDBUtil;
import edu.yzu.testspringboot002.utils.password.PasswordUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 我们聊天用户服务
 *
 * @author yulang
 * @date 2023-08-21
 */
@Service
@Slf4j(topic = "WeChatUserService")
public class WeChatUserService {

    @Autowired
    private WxMaService wxMaService;


    @Autowired
    private WxMaProperties wxMaProperties;

    @Autowired
    private DoctorService iDoctorsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

//    @Autowired
//    private DoctorsConvertMapper doctorsConvertMapper;

//    @Autowired
//    private IDictTypeService dictTypeService;

    /**
     * 登录
     */
    public AppUserVO toLogin(WeChatDTO weChatDTO) {
        String code = weChatDTO.getCode();
        log.info("code: {}", code);
        if (StrUtil.isBlank(code)) {
            throw new BizException("非法的授权码信息！");
        }
        WxMaProperties.Config config = wxMaProperties.getConfigs().stream().findFirst().get();

        if (!wxMaService.switchover(config.getAppid())) {
            throw new BizException(String.format("未找到对应appid=[%s]的配置，请核实！", config.getAppid()));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            String unionid = session.getUnionid();
            if (!StrUtil.isAllNotBlank(sessionKey, openid)) {
                throw new BizException("登录失败！");
            }
            log.info("current sessionKey : {} ,openId:{}, unionid:{}", sessionKey, openid, unionid);

            RocksDBUtil.put(CacheColumnFamilyConstants.OPEND_ID, openid, sessionKey);

            Doctor doctors = builderUserCache(openid, weChatDTO, unionid);
            if (doctors == null) {
                throw new BizException(4000, "账号审核中，暂不能登录！请联系管理员！");
            }
            return new AppUserVO(openid, doctors);
        } catch (Exception exception) {
            log.error("登录失败： {}", exception.getMessage(), exception);
            throw new BizException(40001, exception.getLocalizedMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }


    public static void main(String[] args) {
        System.out.println(PwdUtil.base64Encode("17671688918"));
    }

    private Doctor builderUserCache(String openid, WeChatDTO weChatDTO, String unionid) {


//        LambdaQueryWrapper<Doctor> queryWrapper = new QueryWrapper<Doctor>().lambda()
//                .eq(Doctor::getDelFlag, 1)
//                .eq(Doctor::getAuditStatus, 1).orderByAsc(Doctor::getCreateTime);
//
//        if (StrUtil.isNotBlank(weChatDTO.getPhone())) {
//            queryWrapper.eq(Doctor::getPhone, PwdUtil.base64Encode(weChatDTO.getPhone())).or()
//                    .eq(Doctor::getOpenId, openid);
//        } else {
//            queryWrapper.eq(Doctor::getOpenId, openid);
//        }
//
//        List<Doctor> doctorsList = iDoctorsService.list(queryWrapper);
//        if (CollUtil.isNotEmpty(doctorsList)) {
//            Doctor doctors = doctorsList.get(0);
//
//            log.info("查询的用户：{}", JSON.toJSONString(doctors));
//
//            doctors = doctorsConvertMapper.toExchangeDeptCodeOne(doctors);
//
//
////            if (StrUtil.isNotBlank(weChatDTO.getPhone()) && StrUtil.isBlank(doctors.getPhone())) {
////                doctors.setPhone(weChatDTO.getPhone());
////            }
//            if (StrUtil.isBlank(doctors.getOpenId()) && StrUtil.isNotBlank(openid)) {
//                doctors.setOpenId(openid);
//            }
//            if (StrUtil.isBlank(doctors.getUnionId()) && StrUtil.isNotBlank(unionid)) {
//                doctors.setUnionId(unionid);
//            }
//
//            iDoctorsService.updateById(doctors);
//
////            DictData title = dictTypeService.getDictDataByValue("Title", doctors.getPositionName());
////            doctors.setPositionName(title.getDictLabel());
//
//            // 顶级部门
////            doctors.setCompanyName(RocksDBUtil.getStr(RedisUserKeyConstants.LOCAL_COMPANY_REF, doctors.getCompanyName()));
//            doctors.setPassword("");
//            redisTemplate.opsForValue().set(RedisUserKeyConstants.getOpenIdKey(doctors.getOpenId()), doctors);
//            log.info("查询的用户doctors：{}", JSON.toJSONString(doctors));
//            return doctors;
//        }
        return null;
    }

    /**
     * 处理医生信息
     *
     * @param phoneNumber 手机号
     * @param openId      openId
     * @param unionId     unionId
     * @return {@link Doctor}
     */
    private Doctor handleDoctorInfo(String phoneNumber, String openId, String unionId) {
        // 验证输入参数
//        if (StrUtil.isAllBlank(openId, phoneNumber)) {
//            throw new BizException("用户参数错误！");
//        }
//
//        // 构建查询条件
//        LambdaQueryWrapper<Doctor> queryWrapper = new QueryWrapper<Doctor>().lambda()
//                .eq(Doctor::getDelFlag, 1)   // 未删除
//                .eq(Doctor::getAuditStatus, 1)  // 已审核
//                .orderByAsc(Doctor::getCreateTime);
//
//        // 根据手机号或openid查询医生信息
//        String encodedPhone = StrUtil.isNotBlank(phoneNumber) ? PwdUtil.base64Encode(phoneNumber) : null;
//        if (encodedPhone != null) {
//            queryWrapper.eq(Doctor::getPhone, encodedPhone).or().eq(Doctor::getOpenId, openId);
//        } else {
//            queryWrapper.eq(Doctor::getOpenId, openId);
//        }
//
//        List<Doctor> doctorsList = iDoctorsService.list(queryWrapper);
//        if (CollUtil.isNotEmpty(doctorsList)) {
//            Doctor doctors = doctorsList.get(0);
//
//            // 更新医生信息
//            //doctors.setUserName(userInfo.getNickName());
//            //doctors.setPhone(StrUtil.isNotBlank(encodedPhone) ? phoneNumber : doctors.getPhone());
//            //doctors.setOpenId(openId);
//
//            // 从Redis获取头像URL或使用用户信息中的头像URL
////            if (StrUtil.isNotBlank(doctors.getOpenId())) {
////                Object imgUrl = redisTemplate.opsForValue().get(RedisUserKeyConstants.getUserImgUrlKey(doctors.getOpenId()));
////                doctors.setImgUrl(imgUrl != null ? imgUrl.toString() : userInfo.getAvatarUrl());
////                //doctors.setImgUrl(userInfo.getAvatarUrl());
////            } else {
////                doctors.setImgUrl(userInfo.getAvatarUrl());
////            }
//
//            //首次登录会执行下面的代码
//            // 设置unionId（如果提供）
//            //if doctors.unionId is  null  and unionId  is not blank , then set the unionId
//            if (StrUtil.isBlank(doctors.getUnionId()) && StrUtil.isNotBlank(unionId)) {
//                doctors.setUnionId(unionId);
//            }
//
//            //if doctors.openId is  null  and openId  is not blank , then set the unionId
//            if (StrUtil.isBlank(doctors.getOpenId()) && StrUtil.isNotBlank(openId)) {
//                doctors.setOpenId(openId);
//            }
//
//            // 更新数据库
//            doctors.setUpdateTime(new Date());
//            doctors.setLoginStatus(1);  // 登录状态  1：在线 0：离线
//            iDoctorsService.updateById(doctors);
//
//            // 缓存医生信息
//            if(StrUtil.isNotBlank(phoneNumber)){
//                redisTemplate.opsForValue().set(RedisUserKeyConstants.getPhoneKey(phoneNumber), doctors);
//            }
//            //if open`id is not null, then cache the openId and doctors
//
//
//            if(StrUtil.isNotBlank(openId)) {
//                redisTemplate.opsForValue().set(RedisUserKeyConstants.getOpenIdKey(doctors.getOpenId()), doctors);
//            }
//
//
////            redisTemplate.opsForValue().set(
////                    StrUtil.isNotBlank(phoneNumber) ? RedisUserKeyConstants.getPhoneKey(phoneNumber) : RedisUserKeyConstants.getOpenIdKey(doctors.getOpenId()),
////                    doctors
////            );
//
//            // 转换并返回医生信息（如果需要）
//            // doctors = doctorsConvertMapper.toExchangeDeptCodeOne(doctors); // 根据需要启用或注释掉
//
//            return doctors;
//        }
        return null;
    }

    // loginOut method,parameter is openId
    public String logout(String openId) {
//        if (StrUtil.isBlank(openId)) {
//            throw new BizException("用户信息不存在！");
//        }
//        Doctor doctors = iDoctorsService.getOne(Wrappers.<Doctor>lambdaQuery().eq(Doctor::getOpenId, openId));
//        if (doctors == null) {
//            throw new BizException("用户信息不存在！");
//        }
//        doctors.setLoginStatus(0);
//        iDoctorsService.updateById(doctors);
//        return openId;
        return null;
    }



    public AppUserInfo getPhone(WeChatDTO weChatDTO) {
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(weChatDTO.getCode());

            log.info("phone: {}, {} ,{} ,{}", phoneNoInfo.getPhoneNumber(), phoneNoInfo.getPurePhoneNumber(), phoneNoInfo.getCountryCode(),
                    phoneNoInfo.getWatermark());

            WxMaUserInfo userInfo = getWxMaUserInfo(weChatDTO);

            weChatDTO.setPhone(phoneNoInfo.getPhoneNumber());


            checkDoctor(phoneNoInfo.getPhoneNumber(), userInfo, weChatDTO.getOpenId());

            Doctor doctors = builderUserCache(weChatDTO.getOpenId(), weChatDTO, "");
            if (doctors == null) {
                throw new BizException("当前用户:" + phoneNoInfo.getPhoneNumber() + "未注册！请先注册！");
            }

            return new AppUserInfo(phoneNoInfo.getPhoneNumber(), userInfo.getAvatarUrl(), userInfo.getNickName(), doctors);

        } catch (Exception exception) {
            log.error("获取手机号失败：{}", exception.getLocalizedMessage(), exception);
            throw new BizException("登录失败");
        }
    }

    //    public ResponseResult<AppUserVO> getUserByWxPhoneCode(@RequestBody WeChatDTO weChatDTO)

//    public AppUserInfo getUserByWxPhoneCode(WeChatDTO weChatDTO) {
//        try {
//            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(weChatDTO.getCode());
//
//            log.info("phone: {}, {} ,{} ,{}", phoneNoInfo.getPhoneNumber(), phoneNoInfo.getPurePhoneNumber(), phoneNoInfo.getCountryCode(),
//                    phoneNoInfo.getWatermark());
//
//
//            //WxMaUserInfo userInfo =wxMaService.getUserService().getUserInfo(weChatDTO.getSessionKey(), weChatDTO.getEncryptedData(), weChatDTO.getIv());
//
//            //WxMaUserInfo userInfo = getWxMaUserInfo(weChatDTO);
//
//            weChatDTO.setPhone(phoneNoInfo.getPhoneNumber());
//
//            String wx_login_code=weChatDTO.getWx_login_code();
//
//            WeChatDTO wx_parameter = new WeChatDTO();
//            wx_parameter.setCode(wx_login_code);
//
//            JSONObject j=getWeChat(wx_parameter);
//            String openId= j.getStr("openId");
//            String unionId= j.getStr("unionId");
//            String sessionKey= j.getStr("sessionKey");
//
//
//
//
//            Doctor doctors=handleDoctorInfo(phoneNoInfo.getPhoneNumber(),  openId, unionId);
//            doctors = doctorsConvertMapper.toExchangeDeptCodeOne(doctors);
//
////            Doctor doctor=checkDoctor(phoneNoInfo.getPhoneNumber(), userInfo, weChatDTO.getOpenId());
////            //下面方法中 似乎和checkDoctor方法重复了一些内容
////            Doctor doctors = builderUserCache(weChatDTO.getOpenId(), weChatDTO, "");
//            if (doctors == null) {
//                throw new BizException("当前用户:" + phoneNoInfo.getPhoneNumber() + "未注册！请先注册！");
//            }
//            //if doctors.imgUrl  is null or empty, then set the imgUrl =https://images.kxymall.com/MjAyMzA4MjcxOTQ3NDQ5MzUzMQ==,
//            if(StrUtil.isBlank(doctors.getImgUrl())){
//                doctors.setImgUrl("https://images.kxymall.com/MjAyMzA4MjcxOTQ3NDQ5MzUzMQ==");
//            }
//
//            return new AppUserInfo(phoneNoInfo.getPhoneNumber(), null, null, doctors);
//
//        } catch (Exception exception) {
//            log.error("获取手机号失败：{}", exception.getLocalizedMessage(), exception);
//            throw new BizException("登录失败");
//        }
//    }

    //这个方法当前似乎不太能用 因为缺乏getEncryptedData 和 getIv 的来源  这个需要和前端沟通

    @NotNull
    private WxMaUserInfo getWxMaUserInfo(WeChatDTO weChatDTO) {

        try {
            String sessionKey = RocksDBUtil.getStr(CacheColumnFamilyConstants.OPEND_ID, weChatDTO.getSessionKey());

            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, weChatDTO.getEncryptedData(), weChatDTO.getIv());

            log.info("user info :{}", userInfo.getAvatarUrl(), userInfo.getNickName());
            log.info("params :{}", JSONUtil.toJsonStr(userInfo));
            return userInfo;
        } catch (Exception e) {
            log.error("获取用户详细信息失败：{}", e.getLocalizedMessage(), e);
            return new WxMaUserInfo();
        }
    }

    private Doctor checkDoctor(String phoneNumber, WxMaUserInfo userInfo, String openId) {

//        if (StrUtil.isAllBlank(openId, phoneNumber)) {
//            throw new BizException("用户参数错误！");
//        }
//
//        List<Doctor> doctorsList = iDoctorsService.list(new QueryWrapper<Doctor>().lambda()
//                .eq(Doctor::getPhone, PwdUtil.base64Encode(phoneNumber))
//                .or().eq(Doctor::getOpenId, openId)
//                .eq(Doctor::getDelFlag, 1)
//                .eq(Doctor::getAuditStatus, 1)
//                .orderByAsc(Doctor::getCreateTime));
//        if (CollUtil.isNotEmpty(doctorsList)) {
//            Doctor doctors = doctorsList.get(0);
//            doctors.setUserName(userInfo.getNickName());
//            doctors.setOpenId(openId);
//            doctors.setPhone(phoneNumber);
//            if (StrUtil.isNotBlank(doctors.getOpenId())) {
//                Object imgUrl = redisTemplate.opsForValue().get(RedisUserKeyConstants.getUserImgUrlKey(doctors.getOpenId()));
//                if (imgUrl != null) {
//                    doctors.setImgUrl(imgUrl + "");
//                }
//            } else {
//                doctors.setImgUrl(userInfo.getAvatarUrl());
//            }
//            doctors.setUpdateTime(new Date());
//            iDoctorsService.updateById(doctors);
//            redisTemplate.opsForValue().set(RedisUserKeyConstants.getPhoneKey(phoneNumber), doctors);
//            return doctors;
//        }
        return null;
    }

    public AppUserVO getUserIfo(WeChatDTO weChatDTO) {

        if (StrUtil.isNotBlank(weChatDTO.getOpenId())) {
            Doctor doctors = builderUserCache(weChatDTO.getOpenId(), weChatDTO, "");  //从数据库查询 同时放入缓存
            if (doctors == null) {
                throw new BizException("用户信息不存在！");
            }
            return new AppUserVO(weChatDTO.getOpenId(), doctors);
        }

        if (StrUtil.isNotBlank(weChatDTO.getPhone())) {
            Doctor doctors = builderByPhoneUserCache(weChatDTO.getPhone());
            if (doctors == null) {
                throw new BizException("用户信息不存在！");
            }
            return new AppUserVO(weChatDTO.getOpenId(), doctors);
        }
        throw new BizException("用户信息不存在！");
    }






    private Doctor builderByPhoneUserCache(String phone) {
//        List<Doctor> doctorsList = iDoctorsService.list(new QueryWrapper<Doctor>().lambda()
//                .eq(Doctor::getDelFlag, 1)
//                .eq(Doctor::getAuditStatus, 1)
//                .eq(Doctor::getPhone, PwdUtil.base64Encode(phone)).orderByAsc(Doctor::getCreateTime));
//        if (CollUtil.isNotEmpty(doctorsList)) {
//            Doctor doctors = doctorsList.get(0);
//            doctors = doctorsConvertMapper.toExchangeDeptCodeOne(doctors);
//            // 顶级部门
////            doctors.setCompanyName(RocksDBUtil.getStr(RedisUserKeyConstants.LOCAL_COMPANY_REF, doctors.getCompanyName()));
//            redisTemplate.opsForValue().set(RedisUserKeyConstants.getOpenIdKey(doctors.getOpenId()), doctors);
//            return doctors;
//        }
        return null;
    }

    /**
     * 登录电话
     *
     * @param weChatDTO 我们聊天dto
     * @return {@link AppUserVO}
     */
    public AppUserVO loginPhone(WeChatDTO weChatDTO) {

        String lockLoginKey = RedisUserKeyConstants.getLockLoginKey(weChatDTO.getPhone());

        if (redisTemplate.hasKey(lockLoginKey)) {
            Long increment = redisTemplate.opsForValue().increment(lockLoginKey);
            if (increment >= 6) {
                throw new BizException("登录失败次数过多，账号已被锁定！");
            }
        }
        //String code = weChatDTO.getCode();


        //加密后的电话号码

        //System.out.println(weChatDTO.getPhone());


        String str = weChatDTO.getPhone();
        String phone= PwdUtil.base64Encode(str);

        System.out.println(phone);
        List<Doctor> doctorsList = iDoctorsService.getDoctorByPhone(phone);
        //List<Doctor> doctorsList = iDoctorsService.list(new LambdaQueryWrapper<Doctor>().eq(Doctor::getPhone, PwdUtil.base64Encode(weChatDTO.getPhone())));
        if (CollUtil.isEmpty(doctorsList)) {
            throw new BizException("用户不存在！");
        }
        Doctor doctor = doctorsList.get(0);
//        if (doctors.getAuditStatus() != 1) {
//            throw new BizException("账号审核中，暂不能登录！请联系管理员！");
//        }

//        doctors.setCompanyName(RocksDBUtil.getStr(RedisUserKeyConstants.LOCAL_COMPANY_REF, doctors.getCompanyName()));
        boolean matches = PasswordUtils.matches(weChatDTO.getPassword(), doctor.getPassword());
        if (!matches) {
            Long increment = redisTemplate.opsForValue().increment(lockLoginKey, 1);
            if (increment <= 1) {
                redisTemplate.expire(lockLoginKey, 30, TimeUnit.MINUTES);
            }
            throw new BizException("密码不正确！");
        }

        int length = weChatDTO.getPassword().length();
        boolean number = NumberUtil.isNumber(weChatDTO.getPassword());


//        String openId = doctors.getOpenId();
//        if (StrUtil.isBlank(openId)) {   // is new user first login ,will set user wx info
//            // 根据code查询微信服务获得openid
//            openId = setdWeChatInfo(weChatDTO);
//            //openId = UUID.randomUUID(true).toString().replace("-", "");
//            doctors.setPassword("");
//            doctors.setOpenId(openId);
//        }
//        doctors = doctorsConvertMapper.toExchangeDeptCodeOne(doctors);
//        redisTemplate.opsForValue().set(RedisUserKeyConstants.getOpenIdKey(doctors.getOpenId()), doctors);

        //return new AppUserVO(openId, doctors, (length < 8 && number));

        return new AppUserVO("", doctor, (length < 8 && number));

    }

    //query  by code
    public String getOpenId(WeChatDTO weChatDTO) {
        String code = weChatDTO.getCode();
        log.info("code: {}", code);
        if (StrUtil.isBlank(code)) {
            throw new BizException("非法的授权码信息！");
        }
        WxMaProperties.Config config = wxMaProperties.getConfigs().stream().findFirst().get();

        if (!wxMaService.switchover(config.getAppid())) {
            throw new BizException(String.format("未找到对应appid=[%s]的配置，请核实！", config.getAppid()));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            String unionid = session.getUnionid();
            if (!StrUtil.isAllNotBlank(sessionKey, openid)) {
                throw new BizException("登录失败！");
            }
            log.info("current sessionKey : {} ,openId:{}, unionid:{}", sessionKey, openid, unionid);

            RocksDBUtil.put(CacheColumnFamilyConstants.OPEND_ID, openid, sessionKey);

            // Doctor doctors = builderUserCache(openid, weChatDTO, unionid);
//            if (doctors == null) {
//                throw new BizException(4000, "人员信息不存在，请联系管理员！");
//            }
            return openid;
        } catch (Exception exception) {
            log.error("获取openId失败： {}", exception.getMessage(), exception);
            throw new BizException(40001, "登录失败:" + exception.getLocalizedMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }


    }


    public void bindWeChat(WeChatDTO weChatDTO) {
        setdWeChatInfo(weChatDTO);
    }


    private String setdWeChatInfo(WeChatDTO weChatDTO) {

//        List<Doctor> doctorsList = iDoctorsService.list(new LambdaQueryWrapper<Doctor>().eq(Doctor::getPhone, PwdUtil.base64Encode(weChatDTO.getPhone()))
//                .eq(Doctor::getAuditStatus, 1));
//        if (CollUtil.isEmpty(doctorsList)) {
//            throw new BizException("医生信息不存在！");
//        }
//
//        Doctor doctors = doctorsList.get(0);
//
//
//        String code = weChatDTO.getCode();
//        log.info("code: {}", code);
//        if (StrUtil.isBlank(code)) {
//            throw new BizException("非法的授权码信息！");
//        }
//        WxMaProperties.Config config = wxMaProperties.getConfigs().stream().findFirst().get();
//
//        if (!wxMaService.switchover(config.getAppid())) {
//            throw new BizException(String.format("未找到对应appid=[%s]的配置，请核实！", config.getAppid()));
//        }
//
//        try {
//            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
//            String sessionKey = session.getSessionKey();
//            String openid = session.getOpenid();
//            String unionid = session.getUnionid();
//            if (StrUtil.isAllBlank(sessionKey, openid)) {
//                throw new BizException("登录失败！");
//            }
//            log.info("current sessionKey : {} ,openId:{}, unionid:{}", sessionKey, openid, unionid);
//            doctors.setUnionId(unionid);
//            doctors.setOpenId(openid);
//            iDoctorsService.updateById(doctors);
//            return openid;
//        } catch (Exception exception) {
//            log.error("登录失败： {}", exception.getMessage(), exception);
//            throw new BizException(40001, "登录失败:" + exception.getLocalizedMessage());
//        } finally {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//        }

        return null; //todo
    }


    /**
     * 更新密码
     *
     * @param passwordUpdateDTO 密码更新dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(PasswordUpdateDTO passwordUpdateDTO) {

//        Doctor doctors = DoctorInfoHolderUtil.get();
//
//        Boolean hasKey = redisTemplate.hasKey(RedisUserKeyConstants.getUpdatePasswordKey(doctors.getPhone()));
//        if (hasKey) {
//            throw new BizException("您已修改过密码,30天内禁止修改!");
//        }
//        doctors = iDoctorsService.getById(doctors.getId());
//
//        if (!PasswordUtils.matches(passwordUpdateDTO.getPassword(), doctors.getPassword())) {
//            throw new BizException("原始密码不正确！");
//        }
//
//        if (StrUtil.equals(passwordUpdateDTO.getPassword(), passwordUpdateDTO.getNewPassword())) {
//            throw new BizException("新/旧密码不能相同！");
//        }
//
//        int check = PasswdStrength.check(passwordUpdateDTO.getNewPassword());
//        // 7 大小写 数字
//        if (check < 7) {
//            throw new BizException("密码强度不够！");
//        }
//        String encode = PasswordUtils.encode(passwordUpdateDTO.getNewPassword());
//        doctors.setPassword(encode);
//        iDoctorsService.updateById(doctors);
//        redisTemplate.opsForValue().set(RedisUserKeyConstants.getUpdatePasswordKey(doctors.getPhone()), 1, 30, TimeUnit.DAYS);
//

    }

    public JSONObject getWeChat(WeChatDTO weChatDTO) {
        String code = weChatDTO.getCode();
        log.info("code: {}", code);
        if (StrUtil.isBlank(code)) {
            throw new BizException("非法的授权码信息！");
        }
        WxMaProperties.Config config = wxMaProperties.getConfigs().stream().findFirst().get();

        if (!wxMaService.switchover(config.getAppid())) {
            throw new BizException(String.format("未找到对应appid=[%s]的配置，请核实！", config.getAppid()));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            String unionid = session.getUnionid();
            if (!StrUtil.isAllNotBlank(sessionKey, openid)) {
                throw new BizException("登录失败！");
            }
            log.info("current sessionKey : {} ,openId:{}, unionid:{}", sessionKey, openid, unionid);
            //new json object
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("openId", openid);
            jsonObject.put("unionId", unionid);
            jsonObject.put("sessionKey", sessionKey);
            jsonObject.put("code", code);
            jsonObject.put("loginFlag", 1);   // 1: online 0: offline
            //产生一个随机数token
            String token = StrUtil.uuid();
            jsonObject.put("token", token);
            //以token为key,将jsonObject存入redis
            redisTemplate.opsForValue().set(token, jsonObject, 30, TimeUnit.MINUTES);
            return jsonObject;   // todo  返回值应该只有token  后面有时间再改
            //return openid;
        } catch (Exception exception) {
            log.error("获取微信信息失败：{}", exception.getLocalizedMessage());
            throw new BizException("获取微信信息失败！");
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    public String codeToPhone(String code) {
//        try {
//            return wxMaService.getUserService().getPhoneNoInfo(code).getPhoneNumber();
//        } catch (Exception exception) {
//            log.error("获取手机号失败：{}", exception.getLocalizedMessage(), exception);
//            throw new BizException("登录失败");
//        }
        return null;
    }

    public Doctor codeToOpenid(String code) {
//        try {
//            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
//
//            Doctor doctors = new Doctor();
//            String openid = session.getOpenid();
//            Doctor one = iDoctorsService.getOne(Wrappers.<Doctor>lambdaQuery().eq(Doctor::getOpenId, openid));
////            Doctor one = iDoctorsService.lambdaQuery().eq(Doctor::getOpenId, openid).one();
//            if (ObjUtil.isNotNull(one)) {
//                return one;
//            }
//            doctors.setOpenId(openid);
//            doctors.setUnionId(session.getUnionid());
//            return doctors;
//        } catch (WxErrorException e) {
//            log.error("获取微信信息失败：{}", e.getLocalizedMessage());
//            throw new BizException("获取微信信息失败！");
//        }
        return  null;  //todo
    }
}
